<template>
  <div class="app-portal-content">
    <div class="app-portal-cnt-hd">
      <slot name="query"></slot>
      <div
        class="app-portal-title ml-2"
      >
        <el-input
          placeholder="按页面名称搜索"
          v-model="queryText"
          size="small"
          class="thin-search-input"
          clearable
          style="width: 220px;"
          @clear="refresh"
          @keyup.enter="refresh"
        >
          <template #prefix>
            <JIcon :icon="DFT_ICONS.search" />
          </template>
        </el-input>
      </div>
      <div class="app-portal-tools"></div>
      <el-button-group>
        <el-button
          type="primary"
          @click="handleShowPageCreate('h5')"
          class="page-create-btn"
          size="small"
        >
          <JIcon :icon="DFT_ICONS.add"/>
          H5
        </el-button>
        <el-button
          type="primary"
          @click="handleShowPageCreate('pc')"
          class="page-create-btn"
          size="small"
        >
          <JIcon :icon="DFT_ICONS.add"/>
          Web
        </el-button>
        <el-button
          type="primary"
          @click="handleShowPageCreate('bs')"
          class="page-create-btn"
          size="small"
        >
          <JIcon :icon="DFT_ICONS.add"/>
          大屏
        </el-button>
        <el-button
          type="success"
          @click="handleShowPageCreate('custom')"
          class="page-create-btn"
          size="small"
        >
          <JIcon :icon="DFT_ICONS.add"/>
          定制
        </el-button>
        <el-button
          type="info"
          @click="handleShowPageCreate('link')"
          class="page-create-btn"
          size="small"
        >
          <JIcon :icon="DFT_ICONS.add"/>
          外链
        </el-button>
      </el-button-group>
    </div>
    <div
      class="page-card-container flex-1 overflow-y-auto"
      v-loading="loading"
    >
      <div
        class="page-card"
        :class="{ 'page-card-web': isPageTypeWeb(p) }"
        v-for="p in pages"
        v-resp="{ type: 'c24', container: 'parent', xlc: 4, lgc: 6, mdc: 6, smc: 8, xsc: 12 }"
      >
        <PageThumb
          :img="p?.cover?.file_path"
          ratio-height="70%"
          :mode="getThumbMode(p)"
        >
          <div
            class="page-code"
            v-text="p.page_code"
            v-copy="p.page_code"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="点击复制"
          />
          <div
            class="page-app"
            v-if="p?.app?.group_name"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="所属应用"
            @click="handleShowModuleSelectWin(p)"
          >{{ p?.app?.group_name }}</div>
          <JIcon
            :icon="DFT_ICONS.eye"
            class="page-card-action preview"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="预览"
            @click="handleShowPagePreview(p)"
          />
          <JIcon
            :icon="isPageTypeDesign(p) ? DFT_ICONS.design : DFT_ICONS.edit"
            class="page-card-action"
            v-tippy="{ arrow: true, placement : 'left' }"
            :content="isPageTypeDesign(p) ? '设计' : '修改'"
            @click="handlePageShowEdit(p)"
          />
          <JIcon
            :icon="DFT_ICONS.formview"
            class="page-card-action view"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="视图配置"
            v-if="p.type !== 4"
            @click="handlePageShowViews(p)"
          />
          <JIcon
            :icon="DFT_ICONS.switch"
            class="page-card-action actions"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="按钮配置"
            v-if="p.type !== 4"
            @click="handlePageShowSetting(p, '1')"
          />
          <JIcon
            :icon="DFT_ICONS.code"
            class="page-card-action lowcode"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="低码开发"
            v-if="p.type !== 3 && p.type !== 4"
            @click="handlePageShowSetting(p, '3')"
          />
          <JIcon
            :icon="p.coverGeneing ? DFT_ICONS.loadingBar: DFT_ICONS.camera"
            class="page-card-action cover"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="生成封面"
            @click="handleGeneCover(p)"/>
          <JIcon
            :icon="DFT_ICONS.delete"
            class="page-card-action delete"
            v-tippy="{ arrow: true, placement : 'left' }"
            content="删除"
            @click="handleDelete(p)"
          />
        </PageThumb>
        <div class="page-info">
          <JIcon
            :icon="$pageUtils.getPageTypeIcon(p)"
            class="page-type"
            :class="{
              'page-type-design': isPageTypeDesign(p),
              'page-type-custom': isPageTypeCustom(p)
            }"
          />
          <div class="page-title" v-text="p.page_name"></div>
        </div>
      </div>
    </div>

    <el-pagination
      @size-change="refresh"
      @current-change="refresh"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="pagination.total"
      class="p-2"
    />

    <el-dialog
      title="定制页面注册"
      v-model="pageCustomShow"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-custom
        :app-id="appId"
        :current-data="pageForm"
        v-if="pageCustomShow"
        @success="handlePageSaveSuccess"
        @cancel="handlePageSaveCancel"
      />
    </el-dialog>

    <el-dialog
      title="外链"
      v-model="pageLinkShow"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-link
        :app-id="appId"
        :current-data="pageForm"
        v-if="pageLinkShow"
        @success="handlePageSaveSuccess"
        @cancel="handlePageSaveCancel"
      />
    </el-dialog>

    <el-dialog
      title="视图管理"
      v-model="pageViewShow"
      :fullscreen="true"
      custom-class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <page-views
        v-if="pageViewShow"
        :show="pageViewShow"
        :page-id="$utils.get(pageForm, 'page_id')"
        :is-view="false"
        @close="pageViewShow = false"
      />
    </el-dialog>
    <el-dialog
      :title="pageSettingWinName"
      v-model="pageSettingShow"
      :fullscreen="true"
      custom-class="m-dialog-fullscreen"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <page-setting
        v-if="pageSettingShow"
        :show="pageSettingShow"
        :step-active="pageSettingStepActive"
        :page-id="$utils.get(pageForm, 'page_id')"
        :is-view="false"
        @close="pageSettingShow = false"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, watch, onMounted} from 'vue';
import _ from 'lodash';
import {
  isPageTypeBs,
  isPageTypeCustom,
  isPageTypeDesign,
  isPageTypeH5,
  isPageTypeLink,
  isPageTypePc,
  isPageTypeWeb
} from './pcommon.js';
import formCustom from './form-custom.vue';
import formLink from './form-link.vue';
import {api} from "@jzl/api";
import {DFT_ICONS} from "@jzl/icons";
import {$WinPage, $WinApps, openCompInWin} from "@jzl/comps";
import { $jui, $pageUtils, $utils } from '@jzl/utils'
import { JzlPageBuilderH5, JzlPageBuilderWeb, JzlPageBuilderScreen } from '@jzl/design'

const props = defineProps({
  appId: {
    type: Number,
    required: true
  },
  queryPageType: {
    type: Number,
    default: 0
  }
});

const pages = ref([]);
const loading = ref(false);
const pagination = reactive({
  page: 1,
  pageSize: 50,
  total: 0
});
const queryText = ref("");

// pages
const pageForm = ref(null);
const pagePreviewShow = ref(false);
const pageCustomShow = ref(false);
const pageLinkShow = ref(false);
const pagePcShow = ref(false);
const pageH5Show = ref(false);
const pageBigScreenShow = ref(false);
const pageViewShow = ref(false);
const pageSettingShow = ref(false);
const pageSettingWinName = ref('');
const pageSettingStepActive = ref('1');

const getThumbMode = (p) => {
  let mode = "";
  if (isPageTypeH5(p)) {
    mode = "h5";
  } else if (isPageTypeBs(p)) {
    mode = "bs";
  } else if (isPageTypeWeb(p)) {
    mode = "web"
  } else if (isPageTypeLink()) {
    mode = "link";
  }

  return mode;
};

const init = async () => {

};

const refresh = async () => {
  loading.value = true;

  let type = [];

  if (props.queryPageType === 26) {
    type = [2, 6];
  } else if (props.queryPageType === 53) {
    type = [5, 3];
  } else if (props.queryPageType === 17) {
    type = [1, 7];
  } else if (props.queryPageType === 367) {
    type = [3, 6, 7];
  } else if (props.queryPageType === 125) {
    type = [1, 2, 5];
  } else {
    type = props.queryPageType;
  }

  let ret = await api.page.getPageList({
    type,
    page_name: queryText.value,
    app_id: props.appId
  }, pagination);

  loading.value = false;
  pages.value = _.get(ret, 'rows', []);
  pagination.total = _.get(ret, 'count', 0);
};

const _delete = async (id) => {
  let ret = await api.page.removePage(id);

  if (ret) {
    refresh();
  }
};

const handleDelete = (it) => {
  if (!it || !it.page_id) {
    return;
  }
  $jui.confirm(`此操作将永久删除该页面【${it.page_name}】, 是否继续?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await _delete(it.page_id);
  }).catch(() => {
    /*this.$message({
        type: 'info',
        message: '已取消删除'
    });*/
  });
};

const handleShowPagePreview = (p) => {
  $WinPage({
    link: {
      pageCode: p?.page_code
    }
    /*pageId: _.get(p, 'page_id'),
    pageCode: _.get(p, 'page_code'),
    page: p*/
  });
};

const handleShowPageCreate = (type) => {
  pageForm.value = null;

  if (type === 'bs' || type === 'h5' || type === 'pc') {
    // let pageUrl = '';
    let comp = null;
    if (type === 'bs') {
      comp = JzlPageBuilderScreen;
      // pageUrl = `/apps/jwdesign/#/builder-web?appId=${props.appId}`
    } else if (type === 'pc') {
      comp = JzlPageBuilderWeb;
      // pageUrl = `/apps/jwdesign/#/builder-pc?appId=${props.appId}`
    } else {
      comp = JzlPageBuilderH5;
      // pageUrl = `/apps/jwdesign/#/builder?appId=${props.appId}`
    }

    openCompInWin(comp, {
      appId: props.appId,
    }, {
      fullscreen: true,
      class: "m-dialog-fullscreen-nh"
    })
    /*$WinPage({
      link: {url: pageUrl},
      config: {theme: "m-dialog-fullscreen-nh", fullscreen: true}
    });*/
  } else if (type === 'link') {
    pageLinkShow.value = true;
  } else {
    pageCustomShow.value = true;
  }
};

const handlePageSaveSuccess = () => {
  pageCustomShow.value = false;
  pageLinkShow.value = false;
  refresh();
};

const handlePageSaveCancel = () => {
  pageCustomShow.value = false;
  pageLinkShow.value = false;
};

const handlePageShowEdit = (p) => {
  pageForm.value = p;

  let pageId = _.get(pageForm.value, 'page_id');

  if (!pageId) return;

  if (isPageTypeDesign(p)) {
    let builderUrl = '';
    let comp = null;
    if (isPageTypeBs(p)) {
      comp = JzlPageBuilderScreen;
      // builderUrl = `/apps/jwdesign/#/builder-web?id=${pageId}&appId=${props.appId}`
    } else if (isPageTypeH5(p)) {
      comp = JzlPageBuilderH5;
      // builderUrl = `/apps/jwdesign/#/builder?id=${pageId}&appId=${props.appId}`
    } else if (isPageTypePc(p)) {
      comp = JzlPageBuilderWeb;
      // builderUrl = `/apps/jwdesign/#/builder-pc?id=${pageId}&appId=${props.appId}`
    }

    openCompInWin(comp, {
      appId: props.appId,
      pageId
    }, {
      fullscreen: true,
      class: "m-dialog-fullscreen-nh"
    })
    /*$WinPage({
      link: {url: builderUrl},
      config: {fullscreen: true, theme: "m-dialog-fullscreen-nh"},
      onClose: () => {
        refresh();
      }
    });*/
  } else if (isPageTypeCustom(p)) {
    pageCustomShow.value = true;
  } else if (isPageTypeLink(p)) {
    pageLinkShow.value = true;
  }
};

const handlePageShowSetting = (p, stepActive = '2') => {
  let name = _.get(p, 'page_name');
  pageForm.value = p;
  pageSettingWinName.value = `【${name}】高级设置`;
  pageSettingShow.value = true;
  pageSettingStepActive.value = stepActive;
};

const handlePageShowViews = (p) => {
  pageForm.value = p;
  pageViewShow.value = true;
};

const handleGeneCover = async (p) => {
  if (!p || !p.page_id) return;

  // this.$set(p, "coverGeneing", true);
  p.coverGeneing = true;
  try {
    await this.$putils.genePageScreenshot(p);
  } catch (e) {
  }

  // this.$set(p, "coverGeneing", false);
  p.coverGeneing = false;

  let newPage = await api.page.getPage(p.page_id);
  _.assignIn(p, newPage);
};

const handleShowModuleSelectWin = (page) => {
  $WinApps({
    onConfirm: async (app) => {
      if (!app || !app.group_id) {
        return;
      }
      let ret = await api.page.pageUpsert({
        page_id: page.page_id,
        app_id: app.group_id
      });

      if (ret) {
        $jui.toast('变更成功！');
        refresh();
      }
    },
    onCancel() {
    }
  });
};

watch(() => [props.appId, props.queryPageType], () => {
  refresh();
});

onMounted(() => {
  init();
  refresh();
});
</script>
